package com.powernode.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.powernode.config.AliyunOssConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.URL;
import java.util.Date;

/**
 * @create: 2024/7/18
 * @author: gyhe10
 * @description: 文件上传控制层
 **/

@Api(tags = "文件上传接口管理")
@RequestMapping("admin/file")
@RestController
public class FileUploadController {

    @Resource
    private AliyunOssConfig aliyunOssConfig;

    /**
     * 上传文件
     * 1. 上传文件的请求方式必须为POST
     * 2. 接收文件的请求参数必须为SpringMVC提供的MultipartFile类型
     *
     * @param file
     * @return
     */
    @ApiOperation("上传单个文件")
    @PostMapping("/upload/element")
    public String uploadFile(MultipartFile file) {

        // Bucket名称
        String bucketName = aliyunOssConfig.getBucketName();

        // 以当前日期为上传文件在bucket中的存储目录
        String newFolderName = DateUtil.format(new Date(), "yyyy-MM-dd");

        // 以时间戳作为文件新名称，避免上传文件重名导致原文件被覆盖
        String newFileName = DateUtil.format(new Date(), "HHmmssSSS");

        // 获取源文件的文件名，例如examplefile.txt
        String originalFilename = file.getOriginalFilename();
        // 获取源文件的后缀名，例如.txt
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如20240101/91269317619236.txt。
        String objectName = newFolderName + "/" + newFileName + fileSuffix;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());

        URL url = null;
        try {
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file.getInputStream());

            // 上传文件
            ossClient.putObject(putObjectRequest);

            // 创建上传文件访问的url地址
            url = ossClient.generatePresignedUrl(bucketName, objectName, DateUtil.offset(new Date(), DateField.YEAR, 10));
        } catch (Exception e) {
            System.out.println("Error Message:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return url.toString();
    }
}
